import requests
import pandas as pd
import matplotlib.pyplot as plt
import time
import matplotlib

matplotlib.use('Agg')  # 非交互模式，只能保存图片
plt.rcParams['font.sans-serif'] = ['SimHei']  # 中文字体
plt.rcParams['axes.unicode_minus'] = False    # 负号正常显示

def fetch_stock(code="sz002392"):

    url = f"https://hq.sinajs.cn/list={code}"
    headers = {
        "Referer": "https://finance.sina.com.cn",
        "User-Agent": "Mozilla/5.0"
    }
    r = requests.get(url, headers=headers)
    r.encoding = "gbk"
    data_str = r.text.strip()
    parts = data_str.split('="')[1].strip('";').split(',')

    result = {
        "name": parts[0],
        "price": float(parts[3]),
        "volume": int(parts[8]),
        "amount": float(parts[9]),
        "date": parts[30],
        "time": parts[31]
    }
    return result

def main_loop(code="sz002392", interval=10):
    df = pd.DataFrame(columns=["datetime", "price", "volume"])

    while True:
        data = fetch_stock(code)
        dt = f"{data['date']} {data['time']}"
        print(f"{dt}  {data['name']}  价格: {data['price']}  成交量: {data['volume']}")

        new_row = pd.DataFrame([[dt, data["price"], data["volume"]]],
                               columns=["datetime", "price", "volume"])
        df = pd.concat([df, new_row], ignore_index=True)
        df["datetime"] = pd.to_datetime(df["datetime"])
        df = df.set_index("datetime")

        # 计算均线
        df["MA5"] = df["price"].rolling(window=5).mean()
        df["MA10"] = df["price"].rolling(window=10).mean()

        # 绘图
        plt.clf()
        plt.plot(df.index, df["price"], label="价格", color="blue")
        plt.plot(df.index, df["MA5"], label="MA5", color="orange")
        plt.plot(df.index, df["MA10"], label="MA10", color="green")
        plt.xlabel("时间")
        plt.ylabel("价格")
        plt.title(f"{data['name']} 分时图")
        plt.legend()
        plt.grid(True)

        plt.savefig("realtime.png", dpi=150, bbox_inches="tight")

        time.sleep(interval)

if __name__ == "__main__":
    main_loop("sz002392", interval=10)
